package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Component
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 处理超时的订单
     */
    @Scheduled(cron = "0 * * * * ?")
    public void processTimeOrder(){
        log.info("处理超时的订单的参数为:{}", LocalDateTime.now());
        LocalDateTime Time = LocalDateTime.now().plusMinutes(-15);

        List<Orders> ordersList = orderMapper.getByStatusAndOrderTimeLT(Orders.UN_PAID, Time);

        if (ordersList != null && ordersList.size() > 0){
            for (Orders orders : ordersList) {
                orders.setStatus(Orders.CANCELLED);
                orders.setOrderTime(LocalDateTime.now());
                orders.setRejectionReason("订单已超时，自动取消");
                orderMapper.update(orders);
            }
        }

    }

    /**
     * 处理派送超时的订单
     */
    @Scheduled(cron = "* * 1 * * ?")
    public void processDeliveryOrder(){
        log.info("处理超时的派送订单的参数为:{}", LocalDateTime.now());
        LocalDateTime Time = LocalDateTime.now().plusMinutes(-60);

        List<Orders> ordersList = orderMapper.getByStatusAndOrderTimeLT(Orders.DELIVERY_IN_PROGRESS, Time);

        if (ordersList != null && ordersList.size() > 0){
            for (Orders orders : ordersList) {
                orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
                orders.setOrderTime(LocalDateTime.now());
                orders.setRejectionReason("派送时间过长，视订单已完成");
                orderMapper.update(orders);
            }
        }

    }
}
